package com.tanhua.manager.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.manager.constant.CacheKey;
import com.tanhua.manager.domain.Admin;
import com.tanhua.manager.exception.BusinessException;
import com.tanhua.manager.interceptor.AdminHolder;
import com.tanhua.manager.mapper.AdminMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
@Service
public class AdminService  {
    @Value("${tanhua.secret}")
    private String secret;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public void cacheCode(String code, String uuid) {
        redisTemplate.opsForValue().set(CacheKey.CODE_PREFIX + uuid, code, Duration.ofMinutes(5));

    }

    public ResponseEntity login(String username, String password, String code, String uuid) {
        String value = redisTemplate.opsForValue().get(CacheKey.CODE_PREFIX + uuid);
        if (value == null || !value.equals(code)) {
            throw new BusinessException("验证码错误");
        }
        Admin admin = adminMapper.selectOne(new LambdaQueryWrapper<Admin>().eq(Admin::getUsername, username));
        if (admin == null) {
            throw new BusinessException("账户错误");
        }
        if (!DigestUtils.md5Hex(password).equals(admin.getPassword())) {
            throw new BusinessException("账户或密码错误");
        }
        String token=Jwts.builder().signWith(SignatureAlgorithm.HS256, secret)
                .claim("id", admin.getId())
                .claim("username", admin.getUsername())
                .compact();
        redisTemplate.opsForValue().set(CacheKey.TOKEN_PREFIX+token, JSON.toJSONString(admin),Duration.ofMinutes(1));
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        return ResponseEntity.ok(result);
    }

    public ResponseEntity profile() {
        Admin admin = AdminHolder.getAdmin();
        admin.setPassword(null);

        return ResponseEntity.ok(admin);
    }

    public ResponseEntity logout() {
        String token = AdminHolder.getToken();
        redisTemplate.delete(CacheKey.TOKEN_PREFIX + token);
        return ResponseEntity.ok(null);
    }
}
